<?php

class Materials_Model_Material_Observer_CategoryUpdater extends Workset_Model_Observer_Abstract {

    protected $_isStored;

    public function beforeSave(Workset_Model_Subject_Interface $material, $data = null) {
        $this->_isStored = null;

        if ($material instanceof Materials_Model_Material) {
            $this->_isStored = $material->isStored();
        }
    }

    /**
     * Добавляет привязку материала к категории
     *
     * @param Workset_Model_Subject_Interface $material
     * @param  $data
     * @return void
     */
	public function afterSave(Workset_Model_Subject_Interface $material, $data = null) {
		if ($material instanceof Materials_Model_Material) {

            if ($material->getCategoryId() > 0) {

                if (false === $this->_isStored) {

                    $material->linkToObject($material->getCategory());

                } elseif (true === $this->_isStored) {

                    $oldData = $material->getOldData();

                    if (is_array($oldData)) {
                        if ($oldData['category_id'] != $material->getCategoryId()) {

                            if ($oldData['category_id'] > 0) {
                                $category = Materials_Model_Category::getInstance($oldData['category_id']);
                                $material->unlinkObject($category);
                            }

                            $material->linkToObject($material->getCategory());
                        }
                    }
                }
            }

        }

        $this->_isStored = null;
	}

}